package com.crishne.anwo.interceptor;

import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.crishne.anwo.model.Log;
import com.crishne.anwo.model.User;
import com.crishne.anwo.service.LogService;
import com.crishne.anwo.service.UserService;

public class LogInterceptor implements HandlerInterceptor {

	@Autowired
	private LogService logService;
	

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		String stIp = arg0.getRemoteAddr();
		String stUrl = arg0.getRequestURI();
		String stUserId = "";
		
		Log log = new Log();
		log.setStLogId(UUID.randomUUID().toString());
		log.setDtLog(new Date());
		log.setStIp(stIp);
		log.setStUrl(stUrl);
		if(null != arg0.getSession().getAttribute("userid") 
				&& !"".equals(arg0.getSession().getAttribute("userid"))){
			stUserId = (String)arg0.getSession().getAttribute("userid");
			User user = (User)arg0.getSession().getAttribute(stUserId);
			log.setStUserId(stUserId);
			log.setStUserName(user.getStUserName());
		}
		
		//解析stUrl字符串，获取几个关键功能方法，记录到stOp字段内
		String methodStr = stUrl.substring(stUrl.lastIndexOf("/")+1, stUrl.lastIndexOf("."));
		if("loginSubmit".equals(methodStr)){
			log.setStOp("登录");
		}
		else if("logout".equals(methodStr)){
			log.setStOp("登出");
		}
		else{
			log.setStOp(methodStr);
		}
		logService.save(log);

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
		return true;
	}

}
